package com.lingkun.demo.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingkun.demo.contants.Constant;
import com.lingkun.demo.exception.BusinessException;
import com.lingkun.demo.exception.code.BaseResponseCode;
import com.lingkun.demo.sys.entity.SysMenu;
import com.lingkun.demo.sys.entity.SysRole;
import com.lingkun.demo.sys.entity.SysUser;
import com.lingkun.demo.sys.entity.sysVo.*;
import com.lingkun.demo.sys.mapper.SysUserMapper;
import com.lingkun.demo.sys.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingkun.demo.utils.JwtTokenUtil;
import com.lingkun.demo.utils.PasswordUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.One;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小龙
 * @since 2021-04-24
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Autowired
    private UserRoleService userRoleService;


    @Override //登录
    public LoginRespVO login(LoginReqVO vo) {
        vo.setType("1");
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",vo.getUsername());
        SysUser sysUser =  baseMapper.selectOne(queryWrapper);
        if(sysUser==null){
            throw  new BusinessException(BaseResponseCode.ACCOUNT_ERROR);
        }
        if(!PasswordUtils.matches(sysUser.getUserSalt(),vo.getPassword(),sysUser.getUserPassword())) {
            throw new BusinessException(BaseResponseCode.ACCOUNT_PASSWORD_ERROR);
        }
        Map<String,Object> claims=new HashMap<>();
        List<String>  roles = sysRoleService.getRole(sysUser.getUserId());
        claims.put(Constant.JWT_USER_NAME,sysUser.getName());  // 用户姓名
        claims.put(Constant.JWT_USER_AVATAR,sysUser.getAvatar());  //
        claims.put(Constant.JWT_USER_INTRODUCTION,sysUser.getIntroduction());  //
        claims.put(Constant.ROLES_INFOS_KEY,roles); //角色信息
        claims.put(Constant.PERMISSIONS_INFOS_KEY,sysMenuService.getPermission(roles));//权限信息
        String access_token = JwtTokenUtil.getAccessToken(sysUser.getUserId(),claims);
        log.info("accesstoken{}-->>",access_token);
        Map<String,Object> refreshTokenClaims=new HashMap<>();
        refreshTokenClaims.put(Constant.JWT_USER_NAME,sysUser.getName());
        String refresh_token=null;
        refresh_token=JwtTokenUtil.getRefreshToken(sysUser.getUserId(),refreshTokenClaims);
        log.info("refreshiToken{}-->>",access_token);
        LoginRespVO loginRespVO=new LoginRespVO();
        loginRespVO.setRefreshToken(refresh_token);
        loginRespVO.setToken(access_token);
        return loginRespVO;
    }

    @Override//获取所以路由信息
    public List<menuOne> getMenus() {
        Map<String,List<String>> list  = roleMenuService.role_menu();
        List<SysMenu>  one  =  sysMenuService.list(null);
        List<menuOne> list1 = new ArrayList<>();
        List<menuOne> list2 = new ArrayList<>();
        for(int i=0;i<one.size();i++){
              menuOne menuOne = new menuOne();
              menuOne.setMenuId(one.get(i).getMenuId());
              menuOne.setPath(one.get(i).getPath());
              menuOne.setName(one.get(i).getName());
              menuOne.setComponent(one.get(i).getComponent());
              menuOne.setRedirect(one.get(i).getRedirect());
              menuOne.setHidden(one.get(i).getHidden());
              menuOne.setAlwaysShow(one.get(i).getAlwaysShow());
              menuOne.setParentId(one.get(i).getParentId());
              menuOne.setChildren(Collections.emptyList());
              menuOne.setPermission(one.get(i).getPermission());
                 menuTwo menuTwo = new menuTwo();
                      menuTwo.setTitle(one.get(i).getTitle());
                      menuTwo.setIcon(one.get(i).getIcon());
                      menuTwo.setNoCache(one.get(i).getNoCache());
                      menuTwo.setAffix(one.get(i).getAffix());
                      menuTwo.setBreadcrumb(one.get(i).getBreadcrumb());
                      menuTwo.setActiveMenu(one.get(i).getActiveMenu());
                      menuTwo.setRoles(list.get(one.get(i).getMenuId()));
             menuOne.setMeta(menuTwo);
            if(menuOne.getParentId()==null||menuOne.getParentId().equals("0")){
                list1.add(menuOne);
             }else { list2.add(menuOne);}
          }
        for (menuOne value : list1) {
            List<menuOne> list21 = new ArrayList<>();
            for (com.lingkun.demo.sys.entity.sysVo.menuOne menuOne : list2) {
                if (value.getMenuId().equals(menuOne.getParentId())) {
                    list21.add(menuOne);
                }
            }
            value.setChildren(list21);
        }
        return list1;
    }

    @Override      //获取全部的用户信息以及用户拥有的角色
    public List<userVo> findAll() {
        List<userVo>  list = new ArrayList<>();
        Map<String, List<roleByUserId>>  map  = userRoleService.userRoles();
        List<SysUser>  list1 = baseMapper.selectList(null);
           for(int i=0;i<list1.size();i++){
               userVo userVo  =  new userVo();
                   userVo.setUserId(list1.get(i).getUserId());
                   userVo.setUserName(list1.get(i).getUserName());
                   userVo.setName(list1.get(i).getName());
                   userVo.setRoles(Collections.emptyList());
               userVo.setRoleList(map.getOrDefault(list1.get(i).getUserId(), Collections.emptyList()));
                   list.add(userVo);
           }
        return list;
    }

    @Override    //给用户分配权限信息
    public void assignUserRoles(String userId, userVo roleList) {



    }


}
